import React, { useEffect, useState, useMemo } from "react";
import dynamic from 'umi/dynamic';
import useIframeMessage from '@/components/useIframeMessage';
import { transformEditorToFormily, sendToParent } from 'utils/comm';
// import MobileSchemaForm, { actionsMobile } from './setupPhoneForm';
import styles from './PhoneForm.less';

let actionsMobile;
const MobileSchemaForm = dynamic({
  loader: () => import('./setupPhoneForm')
    .then((data) => {
      ({ actionsMobile } = data);
      return data;
    }),
  render: (props, Loaded) => {
    const Comp = Loaded.default || Loaded;
    return <Comp {...props} actions={actionsMobile} />;
  },
});


const IS_PHONE = true;

// const defaultFormConfigData = { type: 'object', properties: {}};
const PhoneForm = (props) => {

  const { formConfigData: propsFormConfigData } = props;

  const [initialValues, setInitialValues] = useState(undefined);
  const [editable, setEditable] = useState(true);
  // window.setPE = setEditable;

  const [formConfigData, setFormConfigData] = useState(() => {
    window.React = React;
    return propsFormConfigData || {};
  });

  useEffect(() => {
    sendToParent({type: 'ready'}, '*');
    // alert('sendToParent')
    return  () => {
      window.React = undefined;
    }
  },[]);

  useEffect(() => {
    if (propsFormConfigData) {
      setFormConfigData(propsFormConfigData);
    }
  },[propsFormConfigData]);

  useIframeMessage([ 
    (msg) => {
      if (msg.type === 'formConfig') {
        const { setting, data } = msg;
        if (setting) {
          if (setting.formConfig !== undefined) {
            setFormConfigData(setting.formConfig);
          }
          if (setting.editable !== undefined) {
            setEditable(setting.editable);
          }
        }
        if (data) {
          setInitialValues(data);
        }
      }
      else if (msg.type === 'saveForm') {
        actionsMobile.submit((values) => {
          sendToParent({
            type: 'submitForm',
            data: values,
          });
        });
      }
      else if (msg.type === 'saveDraft') {
        actionsMobile.getFormState(({ values }) => {
        sendToParent({
          type: 'submitDraft',
          data: values,
        });
      });
      }
    },
  ]);

  const newFormConfigData = useMemo(() => transformEditorToFormily(formConfigData, IS_PHONE), [formConfigData]);

  return (
    <div className={styles.mobileForm}>
      <MobileSchemaForm
        previewPlaceholder="-"
        // editable
        editable={editable}
        schema={newFormConfigData || newFormConfigData}
        // actions={actionsMobile}
        // onChange={this.handleFormChange}
        initialValues={initialValues}
      >
        {JSON.stringify(formConfigData) === "{}" && (
          <div className={styles.no_data}>
            <span>暂无表单数据</span>
          </div>
        )}
      </MobileSchemaForm>
    </div>
  );
};

export default PhoneForm;
